package user

import (
	"chat/restful/internal/logic"
	"chat/service/user/user"
	"context"
	"google.golang.org/grpc/status"
	"time"

	"chat/restful/internal/svc"
	"chat/restful/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddFlowedLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddFlowedLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddFlowedLogic {
	return &AddFlowedLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddFlowedLogic) AddFlowed(req *types.UserAppleRequest) error {
	// 群聊 , 好友申请
	id := l.ctx.Value("user_id").(uint64)
	_, err := l.svcCtx.UserRpc.UserFlowed(l.ctx, &user.UserAddRequest{
		Id:      uint64(id),
		BeId:    req.To,
		Message: req.Content,
		Type:    uint32(req.Type),
		Remark:  req.Remark,
	})
	if err != nil {
		logx.Error("l.svcCtx.UserRpc.UserFlowed failed: ", err)
		return err
	}
	message := types.Message{}
	soloChat := logic.NewChatWSLogic(l.ctx, l.svcCtx)
	toID := 0 //想要转发消息的那个人的id
	if req.Type == 3 {
		// 如果该用户登录
		// 单聊 转发
		message = types.Message{
			Id:          "",
			From:        id,     //当前登录用户
			To:          req.To, //想要添加的好友的id
			Type:        3,      // 类型3 好友申请
			ContentType: 1,      //消息类型为1
			Time:        time.Now().Format("2006/01/02 15:04:05"),
			Content:     req.Content,
		}
		toID = int(req.To)
	} else if req.Type == 4 {
		//添加群聊
		//判断该用户加入 创建的群聊数是否超过了最大限制
		groupCount, err := l.svcCtx.UserRpc.SelectMyGroupCount(l.ctx, &user.SelectMyGroupCountRequest{UserId: uint64(id)})
		if err != nil {
			return err
		}
		if groupCount.Count > 50 {
			return status.Error(899, "创建或者加入的群聊数据达到了最大限制")
		}
		// 获取群主id
		resp, _ := l.svcCtx.UserRpc.QueryGroupHost(l.ctx, &user.QueryGroupHostRequest{
			GroupId: req.To,
		})

		toID = int(resp.GroupHostId) //群主id
		message = types.Message{
			Id:          "",
			From:        id,     //当前登录用户
			To:          req.To, //想要申请的群的群id
			Type:        3,      // 类型3 好友申请
			ContentType: 1,      //消息类型为1
			Time:        time.Now().Format("2006/01/02 15:04:05"),
			Content:     req.Content,
		}
	}
	//单聊转发
	soloChat.SingleChat(uint64(toID), message)
	return nil
}
